package queue_stack.stack;

import java.util.NoSuchElementException;

/**
 * 顺序栈的简单实现
 */
public class MyStack<E> {
    private E[] elementData = (E[]) new Object[100];
    private int size;

    public E pop() {
        if (size == 0) {
            throw new NoSuchElementException("栈为空!");
        }
        E ret = elementData[size --];
        return ret;
    }

    public void push(E value) {
        elementData[size ++] = value;
    }

    public E peek() {
        if (size == 0) {
            throw new NoSuchElementException("栈为空!");
        }
        return elementData[size - 1];
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < size; i++) {
            sb.append(elementData[i]);
            if (i != size - 1) {
                sb.append(",");
            }
        }
        sb.append("] top");
        return sb.toString();
    }
}
